package com.lanvideo.controller;

import com.lanvideo.entity.LearningRecord;
import com.lanvideo.service.LearningRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学习记录控制器
 */
@RestController
@RequestMapping("/api/learning")
public class LearningRecordController {

    @Autowired
    private LearningRecordService learningRecordService;

    /**
     * 开始学习
     */
    @PostMapping("/start")
    public ResponseEntity<Map<String, Object>> startLearning(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            learningRecordService.startLearning(userId, videoId);
            
            result.put("success", true);
            result.put("message", "开始学习");
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "开始学习失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 更新学习进度
     */
    @PostMapping("/progress")
    public ResponseEntity<Map<String, Object>> updateProgress(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            Integer duration = (Integer) request.get("duration");
            Integer currentPosition = (Integer) request.get("currentPosition");
            Integer totalDuration = (Integer) request.get("totalDuration");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            if (duration == null) duration = 0;
            if (currentPosition == null) currentPosition = 0;
            if (totalDuration == null) totalDuration = 0;
            
            // 计算学习进度
            BigDecimal progress = learningRecordService.calculateProgress(currentPosition, totalDuration);
            
            learningRecordService.updateLearningProgress(userId, videoId, duration, currentPosition);
            
            result.put("success", true);
            result.put("progress", progress);
            result.put("message", "学习进度已更新");
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新学习进度失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 完成学习
     */
    @PostMapping("/complete")
    public ResponseEntity<Map<String, Object>> completeLearning(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            learningRecordService.completeLearning(userId, videoId);
            
            result.put("success", true);
            result.put("message", "学习完成");
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "完成学习失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户的学习记录
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserLearningRecords(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的记录，或者管理员可以查看所有记录
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<LearningRecord> records = learningRecordService.getUserLearningRecords(userId);
            result.put("success", true);
            result.put("records", records);
            result.put("count", records.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取学习记录失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户对特定视频的学习记录
     */
    @GetMapping("/user/{userId}/video/{videoId}")
    public ResponseEntity<Map<String, Object>> getUserVideoLearningRecord(@PathVariable Integer userId, 
                                                                         @PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的记录，或者管理员可以查看所有记录
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            LearningRecord record = learningRecordService.getUserVideoLearningRecord(userId, videoId);
            result.put("success", true);
            result.put("record", record);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取学习记录失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户的学习统计
     */
    @GetMapping("/stats/{userId}")
    public ResponseEntity<Map<String, Object>> getUserLearningStats(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的统计，或者管理员可以查看所有统计
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            LearningRecord stats = learningRecordService.getUserLearningStats(userId);
            result.put("success", true);
            result.put("stats", stats);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取学习统计失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取最近学习记录
     */
    @GetMapping("/recent/{userId}")
    public ResponseEntity<Map<String, Object>> getRecentLearningRecords(@PathVariable Integer userId, 
                                                                       @RequestParam(defaultValue = "5") int limit, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的记录，或者管理员可以查看所有记录
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<LearningRecord> records = learningRecordService.getRecentLearningRecords(userId, limit);
            result.put("success", true);
            result.put("records", records);
            result.put("count", records.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取最近学习记录失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
}
